package org.jeecg.common.file;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.file.annotation.Upload;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 文件上传切面
 *
 * @author jiangtianyi
 * @version 1.0
 * @date 2023-03-02
 */
@Aspect
@Component
public class FileUploadAspect {

    @Pointcut("@annotation(org.jeecg.common.file.annotation.Upload)")
    public void pointCut() {
    }

    /**
     * Around切面，限制文件上传
     *
     * @param point  {@link ProceedingJoinPoint}
     * @param upload {@link Upload}
     * @return 文件上传限定：上传文件大小超出限制、上传文件类型不符合条件
     * @since 1.0
     */
    @Around("pointCut() && @annotation(upload)")
    public Object around(ProceedingJoinPoint point, Upload upload) throws Throwable {
        MultipartHttpServletRequest multipartHttpServletRequest = FileRequestCommon.getMultipartHttpServletRequest();
        // 获取上传文件对象
        MultipartFile file = multipartHttpServletRequest.getFile(FileRequestCommon.FILE);
        if (file == null) {
            throw new RuntimeException("上传文件不允许为空");
        }
        if (!FileTypeEnum.contains(upload.types(), file.getContentType())) {
            return Result.error(upload.nonTypeMessage());
        }
        if (file.getSize() > upload.size()) {
            return Result.error(upload.oversizeMessage());
        }
        return point.proceed();
    }

}